package com.software.course.controller;

import com.software.course.enity.Course;
import com.software.course.enity.User;
import com.software.course.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("/studentRole")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/listCourses")
    public String listCourse(Model model){
        List<Course> courses = studentService.listCourse();
        model.addAttribute("courses",courses);
        return "tables/courseInfo";
    }

    @GetMapping("/uploadFrom")
    public String touploadFrom(){
        return "/studentRole/uploadFrom";
    }


    @PostMapping("/upload")
    public String upload(@RequestParam("text") String text,
                         @RequestPart("file") MultipartFile file,
                        RedirectAttributes attributes,
                        HttpSession session  ) throws IOException {

        User loginUser = (User) session.getAttribute("loginUser");
        log.info("上传信息：text={},file={}",text,file.getSize());
        String originalFilename = file.getOriginalFilename();
  //      获取文件后缀
        String extension = "."+FilenameUtils.getExtension(file.getOriginalFilename());
//        生成新文件名,通过输入信息加上后缀名
        String newFilename = text+extension;
//        处理文件上传 真实路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        if(!text.isEmpty()){
            file.transferTo(new File(realPath+"/",newFilename));
            com.software.course.enity.File file1 = new com.software.course.enity.File();
            file1.setFileName(newFilename);
//            获取session中的userid
            file1.setUserId(loginUser.getId());
            studentService.saveFile(file1);

        }else {
            attributes.addFlashAttribute("message","文件名不能为空,请重新上传");
        }
        return "redirect:/studentRole/uploadFrom";
    }


}
